const path = require('path')
const fs = require('fs')
const baseConfig = require('../base-config')

const ResponseModel = require('../models/response-model')

module.exports = {
    // 上传
    'post::/resource/upload': async (ctx) => {
        
        // 上传单个文件
        const file = ctx.request.files.file; // 获取上传文件

        const fileName = file.name

        const saveFilePath = path.join( baseConfig.configPath , 'torrents', fileName )
        
        // 创建文件夹
        fs.mkdirSync(path.dirname(saveFilePath), { recursive: true })

        // 创建可读流
        const reader = fs.createReadStream(file.path);
        // 创建可写流
        const upStream = fs.createWriteStream(saveFilePath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);

        // fs.renameSync(file.path, saveFilePath)

        ctx.response.body = ResponseModel.success({ name: fileName })
    },

    // 下载
    'get::/resource/download': async (ctx) => {
        const { name } = ctx.request.query
        if (name) {
            const filePath = path.join( baseConfig.configPath , 'torrents', name )
            const fstat =  fs.statSync(filePath)
            if (fstat.isFile()) {
                ctx.type = path.extname(filePath);
                ctx.body = fs.createReadStream(filePath);
            }
        }
    },
}
  